$(function() {
    $("body").i18n();
    $('#peopleGrid').datagrid({
        toolbar : '#datagrid-toolbar',
        url : contextPath + '/sample/findPageByPeople.pvt',
        //title : "<span id='propleGrid_title'>&nbsp;</span>",
        pagination : true,
        pageSize : 10,
        rownumbers : true,
        striped : true,
        singleSelect : true,
        idField : 'id',
        nowrap : false,
        pagePosition : 'top',
        totalProperty : "total",
        rowsProperty : "peoples",
        frozenColumns : [[{
            field : 'id',
            checkbox : true
        }]],
        columns : [[{
            field : 'name',
            width : 140,
            title : $.i18n.get('people.name'),
            sortable : true
        }, {
            field : 'age',
            align : 'center',
            width : 100,
            title : $.i18n.get('people.age'),
            sortable : true
        }, {
            field : 'gender',
            align : 'center',
            width : 120,
            title : $.i18n.get('people.gender'),
            formatter : function(value, row, index) {
                if (value == '1') {
                    return $.i18n.get("gender.male");
                }
                if (value == '2') {
                    return $.i18n.get("gender.female");
                }
                return value;
            }
        }, {
            field : 'birthday',
            align : 'center',
            width : 100,
            title : $.i18n.get('people.birthday'),
            formatter : formatStringDate
        }, {
            field : 'workTime',
            align : 'center',
            width : 100,
            title : $.i18n.get('people.workTime'),
            formatter : formatStringTime
        }]],
        onBeforeLoad : function(param) {
            if (!$("#queryForm").form('validate')) {
                return false;
            }
            $.extend(param, $('#queryForm').serializeJson());
            return true;
        }
    });

    function formatStringDate(value) {
        return (value == '' || value == null) ? '' : value.substr(0, 10);
    }

    function formatStringTime(value) {
        return value == '' ? '' : value.substr(11, 5);
    }

    window.onSearch = function() {
        $('#peopleGrid').datagrid('clearSelections').datagrid('load', {})
    }

    $("#peopleDialog").dialog({
        closed : true
    });

    window.onReset = function(){
        $('#peopleForm').form('reset');
        if (window.isEditing && window.editRow != undefined && window.editRow != null) {
            var formData = $.extend({}, window.editRow);
            formData.birthday = formatStringDate(formData.birthday);
            formData.workTime = formatStringTime(formData.workTime);
            $('#peopleForm').form('load', formData);
        } else {
            $('#peopleForm').form('load', {
                age : 18,
                gender : 1,
                birthday : '1989-05-01',
                workTime : '09:00'
            });
        }
    }

    window.onSave = function() {
        if ($("#peopleForm").form("validate")) {
            var people = $("#peopleForm").serializeJson();
            if (window.isEditing) {
                people.id = window.editRow.id;
            }
            if (people.workTime != '') {
                people.workTime = "2015-01-01 " + people.workTime
            }
            doSave({
                people : people
            });
            return false;
        }
        return false;
    }

    function doSave(paramData) {
        $.messager.progress({
            title : $.i18n.get('prompt'),
            msg : $.i18n.get('waitingMessage')
        });
        $.ajax({
            type : 'post',
            url : contextPath + "/sample/savePeople.pvt",
            data : JSON.stringify(paramData),
            contentType : 'application/json; charset=UTF-8',
            processData : false,
            dataType : 'json',
            success : function(resp, status, xhr) {
                $.messager.progress('close');
                if (resp.success) {
                    $("#peopleDialog").dialog('close');
                    $.messager.alert($.i18n.get('prompt'), $.i18n.get('saveSuccess'), 'info', function(){
                        onSearch();
                    });
                } else {
                    $.messager.alert($.i18n.get('error'), resp.msg || $.i18n.get("prompt.exception"), 'error');
                }
            },
            error : function(xhr, status, error) {
                $.messager.progress('close');
                $.messager.alert($.i18n.get('error'), error || $.i18n.get("prompt.connection.exception"), 'error');
            }
        });
    }

    window.onAdd = function() {
        window.isEditing = false;
        $("#peopleDialog").dialog({
            title : $.i18n.get('add')
        }).dialog('open');
        onReset();
    }

    window.onEdit = function() {
        var selectedRow = getSelectedRow('#peopleGrid');
        if (selectedRow) {
            window.isEditing = true;
            window.editRow = selectedRow;
            $("#peopleDialog").dialog({
                title : $.i18n.get('edit')
            }).dialog('open');
            onReset();
        }
    }
    window.onDel = function() {
        var selectedRow = getSelectedRow('#peopleGrid', true);
        if (selectedRow) {
            $.messager.confirm($.i18n.get('prompt'), $.i18n.get('confirmDeleteData'), function(result) {
                if (result) {
                    var ids = [];
                    $(selectedRow).each(function() {
                        ids.push(this.id);
                    });
                    $.messager.progress({
                        title : $.i18n.get('prompt'),
                        msg : $.i18n.get('waitingMessage')
                    });
                    $.ajax({
                        url : contextPath + '/sample/deletePeoples.pvt',
                        data : {
                            ids : ids.join(",")
                        },
                        type : "post",
                        success : function(resp) {
                            $.messager.progress('close');
                            if (resp.success == true) {
                                onSearch();
                            } else {
                                $.messager.alert($.i18n.get('error'), resp.msg, 'error');
                            }
                        },
                        error : function(xhr, status, error) {
                            $.messager.progress('close');
                            $.messager.alert($.i18n.get('error'), error || $.i18n.get("prompt.connection.exception"), 'error');
                        }
                    });
                }
            });
        }
    }

    function getSelectedRow(selector, multiple) {
        var selectedRows = $(selector).datagrid('getSelections');
        if (selectedRows.length == 0) {
            showPromptMsg($.i18n.get('selectMinOneRecord'));
            return false;
        } else if (!multiple && selectedRows.length > 1) {
            showPromptMsg($.i18n.get('selectOneRecord'));
            return false;
        } else {
            return multiple ? selectedRows : selectedRows[0];
        }
    }

    function showPromptMsg(msg) {
        $.messager.alert($.i18n.get('prompt'), msg, 'warning');
    }
});